package List;

public class LinkedListWithHead {

    private Node dummyHead;
    //size保存有效的节点个数,不包括dummyHead
    private int size;

    public LinkedListWithHead() {
        this.dummyHead = new Node(-1);
    }

    private static class Node{
        private int val;
        private Node next;

        public Node(int val) {
            this.val = val;
        }
    }

    //头插
    public void addFirst(int val){
        addByIndex(0,val);
    }

    public void addLast(int val){
        addByIndex(this.size,val);
    }
    public void addByIndex(int index,int val){
        if(index<0||index>this.size){
            throw new IllegalArgumentException("add index illegal");
        }
        Node prev = this.dummyHead;
        for (int i = 0; i < index; i++) {
            prev = prev.next;
        }
        Node node = new Node(val);
        node.next = prev.next;
        prev.next = node;
        this.size++;
    }

    public void removeAllVal(int val){
        Node prev = this.dummyHead;
        Node cur = prev.next;
        while (cur!=null){
            if(cur.val==val){
                prev.next = cur.next;
                cur.next = null;
                size--;
            }else {
                prev = prev.next;
            }
            cur = prev.next;
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Node cur = this.dummyHead.next;
        while (cur!=null){
            sb.append(cur.val);
            sb.append("->");
            if(cur.next==null){
                sb.append("NULL");
            }
            cur = cur.next;
        }
        return sb.toString();
    }
}
